package merlin.servlets;

import java.util.Map;

import javax.servlet.ServletContext;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;



public final class ServerManagement implements HttpSessionListener{

	public void sessionCreated(HttpSessionEvent se){
		// do nothing.
		System.out.println(new java.util.Date() + " New session created " + se.getSession().getId() + " with invalidation interval " + se.getSession().getMaxInactiveInterval() + " seconds");
	}

	public void sessionDestroyed(HttpSessionEvent se){
		try{
			// remove the userid from the common hashmap ,
			// if the user has logged in with a username and password.
			HttpSession session = se.getSession();
			System.out.println(new java.util.Date() + " ServerManagement session " + session.getId() + " about to be destroyed ");
	        /*
			String username = (String)session.getAttribute("username");
	        System.out.println("username is " + username);
	        if(username != null){
				Set setLoggedInUsers = (Set)session.getServletContext().getAttribute("setLoggedInUsers");
				boolean removed = setLoggedInUsers.remove(username);
				System.out.println(new java.util.Date() + "User " + username + " removed " + removed);
	        }
	        */
			// remove from the Merlin Reseacher & Free Updates map
			Map mapLoggedInUsers = (Map)session.getServletContext().getAttribute("mapLoggedInUsers");
			if(mapLoggedInUsers != null){
				Object removed = mapLoggedInUsers.remove(session.getId());
				System.out.println(new java.util.Date() + "User " + removed + " removed ");
			}
			// remove from the IW map.
			Map mapIWLoggedInUsers = (Map)session.getServletContext().getAttribute("mapIndustryWatchLoggedInUsers");
			if(mapIWLoggedInUsers != null){
				Object removedIW = mapIWLoggedInUsers.remove(session.getId());
				System.out.println(new java.util.Date() + " IW User " + removedIW + " removed ");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}